package com.aabte.auth.account.resource.api;

import com.aabte.auth.account.domain.exception.AccountAccountOrPasswordException;
import com.aabte.auth.account.resource.api.auth.AuthAccountDTO;
import com.aabte.auth.account.resource.api.auth.AuthApi;
import com.aabte.auth.account.resource.api.auth.AuthCommand;
import com.aabte.auth.account.resource.facade.AuthServiceFacade;
import com.aabte.auth.util.JwtUtil;
import com.aabte.commons.bean.BaseResponse;
import com.aabte.commons.errorcode.ResponseFactory;
import io.jsonwebtoken.Claims;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Validated
@RestController
public class AuthController implements AuthApi {

    @Resource
    private AuthServiceFacade authServiceFacade;

    @Override
    public BaseResponse<String> token(AuthCommand command) {
        try {
            String token = authServiceFacade.token(command.getAccountName(), command.getAccountPassword());
            return ResponseFactory.success(token);
        } catch (AccountAccountOrPasswordException e) {
            throw AccountCode.ACCOUNT_NOT_EXIST_OR_PASSWORD_INCORRECT_EXIST.newException(e);
        }
    }

    @Override
    public BaseResponse<AuthAccountDTO> me(String token) {
        Claims claims = JwtUtil.parseJwt(token);
        String accountId = claims.getSubject();
        AuthAccountDTO authAccountDTO = authServiceFacade.account(accountId);
        return ResponseFactory.success(authAccountDTO);
    }
}
